package org.workhorse.config;

import com.google.inject.*;
import org.workhorse.persistence.Persistence;
import org.workhorse.persistence.jpa.JpaPersistence;
import org.workhorse.persistence.jpa.JpaProfile;

import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityManager;
import javax.annotation.Nullable;
import java.util.Map;

/**
 * @author Brennan Spies
 * <p>Module for configuring a JPA Persistence service.</p>
 *
 */
public class JpaModule extends AbstractModule
{
    /**
     * Configures the module.
     */
    @Override protected void configure() {
        bind(Persistence.class).to(JpaPersistence.class);
        bindConstant().annotatedWith(JpaProfile.class).to("WorkHorse");
        bind(EntityManagerFactory.class).toProvider(EntityManagerFactoryCreator.class);
    }

    @Provides
    public EntityManager getEntityManager(EntityManagerFactory emf) {
       return emf.createEntityManager();
    }

    private static class EntityManagerFactoryCreator implements Provider<EntityManagerFactory>
    {
        private String profile;
        private Map properties;

        EntityManagerFactoryCreator(@JpaProfile String profile, @Nullable Map properties) {
            this.profile = profile;
            this.properties = properties;
        }

        public EntityManagerFactory get() {
            return properties!=null ? javax.persistence.Persistence.createEntityManagerFactory(profile, properties) :
                javax.persistence.Persistence.createEntityManagerFactory(profile);
        }
    }
}
